<template>
  <div class="container">
    <div class="header">
      <el-select v-model="form.semester" placeholder="请选择学期" @change="filterRewards" style="width: 200px; margin-right: 10px;">
        <el-option label="全部学期" :value="null" />
        <el-option v-for="item in semesterOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="form.classId" placeholder="请选择班级" @change="filterRewards" style="width: 200px; margin-right: 10px;">
        <el-option label="全部班级" :value="null" />
        <el-option v-for="item in classOptions" :key="item.classId" :label="item.className" :value="item.classId" />
      </el-select>
      <el-button type="primary" @click="handleAdd">添加奖励记录</el-button>
    </div>

    <el-table
      :data="paginatedRewardList"
      border
      stripe
      highlight-current-row
      style="width: 100%; margin-bottom: 20px; font-size: 11px;"
      v-loading="loading"
      max-height="calc(100vh - 200px)"
      empty-text="暂无数据"
    >
      <el-table-column prop="recordId" label="记录号" width="70" sortable />
      <el-table-column label="学生" width="90" sortable>
        <template #default="scope">
          <el-tag size="small">{{ getStudentName(scope.row.studentId) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="教师" width="90" sortable>
        <template #default="scope">
          <el-tag size="small">{{ getTeacherName(scope.row.teacherId) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="bounsItemId" label="奖励项目ID" width="90" sortable />
      <el-table-column prop="recordTime" label="记录时间" width="100" sortable />
      <el-table-column prop="reviewStatus" label="审核状态" width="90" sortable>
        <template #default="scope">
          <el-tag :type="scope.row.reviewStatus === '已审核' ? 'success' : 'warning'" size="small">
            {{ scope.row.reviewStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="description" label="描述" />
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="scope">
          <el-button-group>
            <el-button size="small" @click="handleEdit(scope.row)" icon="Edit" type="primary">编辑</el-button>
            <el-button size="small" @click="handleDelete(scope.row.recordId)" icon="Delete" type="danger">删除</el-button>
            <el-button 
              size="small" 
              @click="handleReview(scope.row)" 
              icon="Check" 
              type="success" 
              :disabled="scope.row.reviewStatus === '已审核'"
            >
              {{ scope.row.reviewStatus === '已审核' ? '已审核' : '审核' }}
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      layout="total, sizes, prev, pager, next"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: right"
    />

    <!-- 添加/编辑对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="500px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="学期" prop="semester">
          <el-select v-model="form.semester" placeholder="请选择学期" style="width: 100%">
            <el-option v-for="item in semesterOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="班级" prop="classId">
          <el-select v-model="form.classId" placeholder="请选择班级" style="width: 100%">
            <el-option v-for="item in classOptions" :key="item.classId" :label="item.className" :value="item.classId" />
          </el-select>
        </el-form-item>
        <el-form-item label="学生ID" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学生ID" />
        </el-form-item>
        <el-form-item label="教师ID" prop="teacherId">
          <el-input v-model="form.teacherId" placeholder="请输入教师ID" />
        </el-form-item>
        <el-form-item label="奖励项目ID" prop="bounsItemId">
          <el-input v-model="form.bounsItemId" placeholder="请输入奖励项目ID" />
        </el-form-item>
        <el-form-item label="奖励等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择奖励等级" style="width: 100%">
            <el-option label="三等奖学金" value="三等奖学金" />
            <el-option label="二等奖学金" value="二等奖学金" />
            <el-option label="一等奖学金" value="一等奖学金" />
            <el-option label="优秀学生" value="优秀学生" />
            <el-option label="优秀毕业生" value="优秀毕业生" />
          </el-select>
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTime">
          <el-date-picker v-model="form.recordTime" type="date" placeholder="选择日期" style="width: 100%"
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="审核状态" prop="reviewStatus">
          <el-input v-model="form.reviewStatus" disabled />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- OCR 上传组件 -->
    <el-upload
      action="#"
      :on-change="handleOCR"
      :auto-upload="false"
      :show-file-list="false"
    >
      <el-button type="primary" :loading="ocrLoading">上传图片并识别</el-button>
    </el-upload>

    <!-- OCR 识别结果 -->
    <el-input
      v-if="ocrResult"
      type="textarea"
      :rows="4"
      v-model="ocrResult"
      placeholder="OCR 识别结果"
      readonly
    />
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import api from '../api/request'
import axios from 'axios'

const rewardList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加奖励记录')
const formRef = ref(null)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 学期和班级选项
const semesterOptions = ref(['2023-2024-1', '2023-2024-2'])
const classOptions = ref([
  { classId: '1', className: '23级区块链' },
  { classId: '2', className: '23级区块链二班' },
  { classId: '3', className: '23级软件开发班' },
  { classId: '4', className: '23级区块链3班' }
])

const form = reactive({
  recordId: null,
  studentId: '',
  teacherId: '',
  bounsItemId: '',
  level: '三等奖学金',
  recordTime: new Date().toISOString().split('T')[0],
  reviewStatus: '未审核',
  description: '',
  semester: null,
  classId: null
})

const rules = {
  studentId: [{ required: true, message: '请输入学生ID', trigger: 'blur' }],
  teacherId: [{ required: true, message: '请输入教师ID', trigger: 'blur' }],
  bounsItemId: [{ required: true, message: '请输入奖励项目ID', trigger: 'blur' }],
  level: [{ required: true, message: '请选择奖励等级', trigger: 'change' }],
  recordTime: [{ required: true, message: '请选择记录时间', trigger: 'change' }],
  reviewStatus: [{ required: true, message: '请选择审核状态', trigger: 'change' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }]
}

// 添加学生和教师数据
const studentList = ref([]);
const teacherList = ref([]);

// OCR 相关状态
const ocrResult = ref('');
const ocrLoading = ref(false);

// 获取奖励记录
const fetchRewards = async () => {
  loading.value = true
  try {
    const res = await api.reward.getAll()
    if (res.code === 1) {
      rewardList.value = res.data || []
      total.value = rewardList.value.length
    } else {
      ElMessage.error(res.msg || '获取奖励记录失败')
    }
  } catch (error) {
    console.error('获取奖励记录出错:', error)
    ElMessage.error('获取奖励记录失败')
  } finally {
    loading.value = false
  }
}

// 计算属性：过滤后的奖励记录
const filteredRewardList = computed(() => {
  let result = rewardList.value
  if (form.semester && form.semester !== '') {
    result = result.filter(item => item.semester === form.semester)
  }
  if (form.classId && form.classId !== '') {
    result = result.filter(item => item.classId.toString() === form.classId.toString())
  }
  return result
})

// 计算属性：分页后的奖励记录
const paginatedRewardList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredRewardList.value.slice(start, end)
})

// 确保在数据更新时重置分页
watch(filteredRewardList, () => {
  currentPage.value = 1
  total.value = filteredRewardList.value.length
})

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 监听筛选条件变化
watch([() => form.semester, () => form.classId], () => {
  currentPage.value = 1
  total.value = filteredRewardList.value.length
})

// 获取学生和教师数据
onMounted(async () => {
  loading.value = true;
  try {
    // 并行加载学生、教师和奖励数据
    const [studentsRes, teachersRes, rewardsRes] = await Promise.all([
      api.student.getAll(),
      api.teacher.getAll(),
      api.reward.getAll()
    ]);

    studentList.value = studentsRes.data || [];
    teacherList.value = teachersRes.data || [];

    if (rewardsRes.code === 1) {
      rewardList.value = rewardsRes.data || [];
      total.value = rewardList.value.length;
    } else {
      ElMessage.error(rewardsRes.msg || '获取奖励记录失败');
    }
  } catch (error) {
    console.error('加载数据出错:', error);
    ElMessage.error('加载数据失败');
  } finally {
    loading.value = false;
  }
});

// 映射学生ID为学生名称
const getStudentName = (studentId) => {
  if (!studentId) {
    console.warn('学生ID为空:', studentId);
    return '未知学生';
  }
  const student = studentList.value.find(item => item.studentId === Number(studentId));
  if (!student) {
    console.warn('未找到匹配的学生:', studentId, '学生列表:', studentList.value);
  }
  return student ? student.name : '未知学生';
};

// 映射教师ID为教师名称
const getTeacherName = (teacherId) => {
  if (!teacherId) {
    console.warn('教师ID为空:', teacherId);
    return '未知教师';
  }
  const teacher = teacherList.value.find(item => item.teacherId === Number(teacherId));
  if (!teacher) {
    console.warn('未找到匹配的教师:', teacherId, '教师列表:', teacherList.value);
  }
  return teacher ? teacher.name : '未知教师';
};

// 添加奖励记录
const handleAdd = () => {
  dialogTitle.value = '添加奖励记录'
  form.recordId = null
  form.studentId = ''
  form.teacherId = ''
  form.bounsItemId = ''
  form.level = '三等奖学金'
  form.recordTime = new Date().toISOString().split('T')[0]
  form.reviewStatus = '未审核'
  form.description = ''
  form.semester = null
  form.classId = null
  dialogVisible.value = true
}

// 编辑奖励记录
const handleEdit = (row) => {
  dialogTitle.value = '编辑奖励记录'
  Object.assign(form, {
    recordId: row.recordId,
    studentId: row.studentId,
    teacherId: row.teacherId,
    bounsItemId: row.bounsItemId,
    level: row.level,
    recordTime: row.recordTime,
    reviewStatus: row.reviewStatus,
    description: row.description,
    semester: row.semester,
    classId: row.classId
  })
  dialogVisible.value = true
}

// 删除奖励记录
const handleDelete = async (id) => {
  try {
    const res = await api.reward.delete(id);
    if (res.code === 1) {
      ElMessage.success(res.msg || '删除成功');
      fetchRewards();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    console.error('删除奖励记录出错:', error);
    ElMessage.error(error.response?.data?.msg || '删除奖励记录出错');
  }
};

// 审核奖励记录
const handleReview = async (row) => {
  try {
    await ElMessageBox.confirm('确定要审核通过该奖励记录吗？', '审核确认', {
      confirmButtonText: '通过',
      cancelButtonText: '取消',
      type: 'warning'
    });

    const res = await api.reward.review(row.recordId);
    if (res.code === 1) {
      ElMessage.success('审核成功');
      const index = rewardList.value.findIndex(item => item.recordId === row.recordId);
      if (index !== -1) {
        rewardList.value[index].reviewStatus = '已审核';
        // 强制更新视图
        rewardList.value = [...rewardList.value];
      }
    } else {
      ElMessage.error(res.msg || '审核失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('审核奖励记录出错:', error);
      ElMessage.error('审核失败: ' + (error.message || '未知错误'));
    }
  }
};

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res
        if (form.recordId) {
          res = await api.reward.update(form)
        } else {
          res = await api.reward.add(form)
        }

        if (res.code === 1) {
          ElMessage.success(form.recordId ? '更新成功' : '添加成功')
          dialogVisible.value = false
          fetchRewards()
        } else {
          ElMessage.error(res.msg || (form.recordId ? '更新失败' : '添加失败'))
        }
      } catch (error) {
        console.error(form.recordId ? '更新奖励记录出错:' : '添加奖励记录出错:', error)
        ElMessage.error(form.recordId ? '更新失败' : '添加失败')
      }
    }
  })
}

// 上传图片并调用 OCR 接口
const handleOCR = async (file) => {
  ocrLoading.value = true;
  const formData = new FormData();
  formData.append('file', file.raw); // 注意：file.raw 是上传的原始文件

  try {
    const response = await axios.post('/api/ocr/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    ocrResult.value = response.data;
    parseOCRResult(ocrResult.value); // 解析 OCR 结果并填充表单
    ElMessage.success('OCR 识别成功');
  } catch (error) {
    console.error('OCR 识别失败:', error);
    ElMessage.error('OCR 识别失败');
  } finally {
    ocrLoading.value = false;
  }
};

// 解析 OCR 结果并填充表单
const parseOCRResult = (text) => {
  // 假设 OCR 结果包含学生 ID、奖励等级和描述
  const studentIdMatch = text.match(/学生ID[:：]?\s*(\d+)/i);
  const levelMatch = text.match(/奖励等级[:：]?\s*(\S+)/i);
  const descriptionMatch = text.match(/描述[:：]?\s*(.+)/i);

  if (studentIdMatch) form.studentId = studentIdMatch[1];
  if (levelMatch) form.level = levelMatch[1];
  if (descriptionMatch) form.description = descriptionMatch[1];

  // 如果识别结果不符合预期，提示用户手动输入
  if (!studentIdMatch || !levelMatch || !descriptionMatch) {
    ElMessage.warning('OCR 识别结果不完整，请手动输入');
  }
};

const filterRewards = () => {
  console.log('当前选择的班级ID:', form.classId) // 添加日志
  // 根据 classId 过滤奖励记录的逻辑
}
</script>

<style scoped>
.container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
</style>